package com.taoyibao.hongcanting.ui.home.delegate;

import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.taoyibao.hongcanting.R;
import com.taoyibao.hongcanting.base.delegate.BackToolbarDelegate;
import com.taoyibao.hongcanting.base.delegate.ToolbarDelegate;
import com.taoyibao.hongcanting.cache.SpUtils;
import com.taoyibao.hongcanting.event.EventUpdataCart;
import com.taoyibao.hongcanting.model.CartSimpleInfoModel;
import com.taoyibao.hongcanting.model.DishModel;
import com.taoyibao.hongcanting.model.FoodTypeModel;
import com.taoyibao.hongcanting.ui.home.activity.DishDetailsActivity;
import com.taoyibao.hongcanting.ui.home.activity.ShoppingCartActivity;
import com.taoyibao.hongcanting.ui.home.activity.SubmitOrdersActivity;
import com.taoyibao.hongcanting.ui.home.views.ItemMenuListArea;
import com.taoyibao.hongcanting.ui.home.views.ItemMenuRecommendArea;
import com.taoyibao.hongcanting.utils.CodeUtils;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

/**
 * @author TangAnna
 * @description: 点单页面
 * @date :${DATA} 16:41
 */
public class MenuDelegate extends BackToolbarDelegate implements MultiItemTypeAdapter.OnItemClickListener, View.OnClickListener, ToolbarDelegate.OnLeftCilckListener {

    private RecyclerView mRvRecommend;//推荐列表
    private RecyclerView mRvType;//分类列表
    private RecyclerView mRvList;//每个分类下面的列表
    private CommonAdapter mTypeAdapter;//分类
    private CommonAdapter mDishAdapter;//分类下菜品的adapter
    private CommonAdapter mRecommendAdapter;//推荐菜品
    private List<FoodTypeModel> mTypeData;//分类的数据集合
    private List<DishModel> mDishData;//菜品数据集合
    private List<DishModel> mRecommendData;//推荐菜品数据

    @Override
    public int getRootLayoutId() {
        return R.layout.activity_menu;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void initWidget() {
        super.initWidget();
        setTitle("点餐");
        setOnLeftCilckListener(this);
        setLoadingView();
        mRvRecommend = get(R.id.rv_menu_recommend);
        mRvRecommend.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));
        mRvType = get(R.id.rv_menu_type);
        mRvType.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        mRvList = get(R.id.rv_menu_list);
        mRvList.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        get(R.id.layout_showCart).setOnClickListener(this);

        mTypeData = new ArrayList<>();
        mDishData = new ArrayList<>();
        mRecommendData = new ArrayList<>();

        setData();

        //设置菜单页面的赠送View的站位View
        if (!TextUtils.isEmpty(SpUtils.getOtherSeatName())) {
            get(R.id.view_menu_zengSong).setVisibility(View.VISIBLE);
        } else {
            get(R.id.view_menu_zengSong).setVisibility(View.GONE);
        }

    }

    /**
     * 绑定适配器
     */
    private void setData() {
        //分类Adapter
        mRvType.setAdapter(mTypeAdapter = new CommonAdapter<FoodTypeModel>(getActivity(), R.layout.item_menu_type, mTypeData) {
            @Override
            protected void convert(ViewHolder viewHolder, FoodTypeModel foodTypeModel, int position) {
                //分类名称
                TextView tvName = viewHolder.getView(R.id.tv_type_name);
                if (!TextUtils.isEmpty(foodTypeModel.class_name)) {
                    tvName.setText(foodTypeModel.class_name);
                }
                //给分类在购物车中的数据
                TextView tvCount = viewHolder.getView(R.id.tv_item_menu_addCount);
                if (foodTypeModel.class_count == 0) {
                    tvCount.setVisibility(View.GONE);
                } else {
                    tvCount.setVisibility(View.VISIBLE);
                    tvCount.setText(foodTypeModel.class_count + "");
                }
                //设置选中状态
                if (foodTypeModel.isChecked) {//选中
                    viewHolder.getConvertView().setBackgroundColor(CodeUtils.getIdColor(R.color.white));
                } else {//未选中
                    viewHolder.getConvertView().setBackgroundColor(CodeUtils.getIdColor(R.color.colorf5));
                }
            }
        });
        mTypeAdapter.setOnItemClickListener(this);

        //分类下菜品
        mRvList.setAdapter(mDishAdapter = new CommonAdapter<DishModel>(getActivity(), R.layout.item_menu_list_shell, mDishData) {
            @Override
            protected void convert(ViewHolder viewHolder, DishModel dishModel, int i) {
                ItemMenuListArea itemMenuListArea = (ItemMenuListArea) viewHolder.getConvertView();
                itemMenuListArea.setData(dishModel);
            }
        });
        //分类中菜品的点击事件
        mDishAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                DishDetailsActivity.open(getActivity(), mDishData.get(position));
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

        //推荐菜品
        mRvRecommend.setAdapter(mRecommendAdapter = new CommonAdapter<DishModel>(getActivity(), R.layout.item_menu_recommend_shell, mRecommendData) {
            @Override
            protected void convert(ViewHolder viewHolder, DishModel dishModel, int position) {
                ItemMenuRecommendArea mItemView = viewHolder.getView(R.id.layout_itemMenuRecommend_area);
                mItemView.setData(dishModel);
            }
        });
        //推荐菜品的点击事件
        mRecommendAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                DishDetailsActivity.open(getActivity(), mRecommendData.get(position));
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
    }


    /**
     * 设置推荐菜品的数据
     */
    public void setRecommendData(List<DishModel> recommendData) {
        if (recommendData == null || recommendData.size() < 1) {
            return;
        }
        mRecommendData.clear();
        mRecommendData.addAll(recommendData);
        mRecommendAdapter.notifyDataSetChanged();
    }

    /**
     * 设置分类数据
     */
    public void setTypeData(List<FoodTypeModel> data) {
        if (data == null || data.size() < 1) {
            return;
        }
        mTypeData.clear();
        mTypeData.addAll(data);
        mTypeAdapter.notifyDataSetChanged();
        //设置第一个分类下的数据
        if (mTypeData != null && mTypeData.size() > 0) {
            List<DishModel> children = mTypeData.get(0).children;
            setDishData(children, data.get(0).class_name);
        }
    }

    /**
     * 分类的点击事件
     *
     * @param view
     * @param viewHolder
     */
    @Override
    public void onItemClick(View view, RecyclerView.ViewHolder viewHolder, int position) {
        setDishData(mTypeData.get(position).children, mTypeData.get(position).class_name);
        //更新选中状态
        for (int i = 0; i < mTypeData.size(); i++) {
            if (i == position) {
                mTypeData.get(position).isChecked = true;
            } else {
                mTypeData.get(i).isChecked = false;
            }
        }
        mTypeAdapter.notifyDataSetChanged();

    }

    @Override
    public boolean onItemLongClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
        return false;
    }

    /**
     * 设置菜品数据
     */
    public void setDishData(List<DishModel> data, String className) {
        if (data == null || data.size() < 1) {
            return;
        }
        for (int i = 0; i < data.size(); i++) {
            data.get(i).class_name = className;
        }
        mDishData.clear();
        mDishData.addAll(data);
        mDishAdapter.notifyDataSetChanged();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.layout_showCart://购物车
                ShoppingCartActivity.open(getActivity(), "");
                break;
            case R.id.btn_includCartBottom_goOrder://去下单
                SubmitOrdersActivity.open(getActivity(), "");
                break;
        }
    }

    /**
     * 设置底部数据
     */
    public void setBottomUI(List<CartSimpleInfoModel> cartSimpleInfoModel) {
        if (cartSimpleInfoModel == null || cartSimpleInfoModel.size() < 1) {//购物车没有数据
            ((Button) get(R.id.btn_includCartBottom_goOrder)).setEnabled(false);
            get(R.id.tv_includCartBottom_totalCount).setVisibility(View.GONE);
            ((TextView) get(R.id.tv_includCartBottom_price)).setText("总价：￥0:00");
            ((TextView) get(R.id.tv_includCartBottom_discountPrice)).setText("已优惠：￥0:00");
            return;
        }
        CartSimpleInfoModel dataModel = cartSimpleInfoModel.get(0);
        if (dataModel.total_num > 0) {
            ((Button) get(R.id.btn_includCartBottom_goOrder)).setEnabled(true);
            get(R.id.btn_includCartBottom_goOrder).setOnClickListener(this);
            get(R.id.tv_includCartBottom_totalCount).setVisibility(View.VISIBLE);
            ((TextView) get(R.id.tv_includCartBottom_totalCount)).setText(dataModel.total_num + "");
        }
        ((TextView) get(R.id.tv_includCartBottom_price)).setText("总价：" + CodeUtils.formatAmountUnit(dataModel.discount_price));
        ((TextView) get(R.id.tv_includCartBottom_discountPrice)).setText("已优惠：" + CodeUtils.formatAmountUnit((dataModel.origin_price - dataModel.discount_price)));
    }

    /**
     * 刷新数据
     *
     * @param eventUpdataCart
     */
    public void onRefrush(EventUpdataCart eventUpdataCart) {
        DishModel dishModel = eventUpdataCart.dishModel;
        int action = eventUpdataCart.action;//操作
        if (dishModel == null) {
            return;
        }
        String dishId;//菜品ID
        String typeId = "";//分类Id
        //获取分类ID
        if (!TextUtils.isEmpty(dishModel.dish_classId)) {
            typeId = dishModel.dish_classId;
        } else if (!TextUtils.isEmpty(dishModel.class_code)) {
            typeId = dishModel.class_code;
        }
        //获取菜品ID
        dishId = dishModel.dish_code;
        //TODO 刷新推荐菜品
        for (int i = 0; i < mRecommendData.size(); i++) {
            if (TextUtils.equals(dishId, mRecommendData.get(i).dish_code)) {
                mRecommendData.get(i).dish_count = dishModel.dish_count;
                mRecommendAdapter.notifyDataSetChanged();
                break;
            }
        }

        //更新喜爱中的数据
        if (mTypeData != null && mTypeData.size() != 0 && TextUtils.equals(mTypeData.get(0).class_code, "000")) {
            if (mTypeData.get(0).children != null && mTypeData.get(0).children.size() > 0) {
                for (int j = 0; j < mTypeData.get(0).children.size(); j++) {
                    if (TextUtils.equals(dishId, mTypeData.get(0).children.get(j).dish_code)) {
                        mTypeData.get(0).children.get(j).dish_count = dishModel.dish_count;
                        break;
                    }
                }
            }
        }

        //刷新分类的数据
        for (int i = 0; i < mTypeData.size(); i++) {
            if (TextUtils.equals(typeId, mTypeData.get(i).class_code)) {
                //更新分类上的数据
                if (action == -1) {//减操作
                    mTypeData.get(i).class_count -= 1;
                } else if (action == 1) {
                    mTypeData.get(i).class_count += 1;
                }
                for (int j = 0; j < mTypeData.get(i).children.size(); j++) {
                    if (TextUtils.equals(dishId, mTypeData.get(i).children.get(j).dish_code)) {
                        mTypeData.get(i).children.get(j).dish_count = dishModel.dish_count;
                        mDishAdapter.notifyDataSetChanged();
                        break;
                    }
                }
                mTypeAdapter.notifyDataSetChanged();
                break;
            }
        }
    }

    /**
     * 关闭按钮
     *
     * @param view
     */
    @Override
    public void onLeftClick(View view) {
        //清除赠送信息
        SpUtils.putOtherSeatName("");
        SpUtils.putOtherSeatId("");
        getActivity().finish();
    }
}
